import React, {PureComponent} from 'react';
import './index.less'
import fetch from '../../../../../fetchAPI'
import {Form, Icon, Button, Input, DatePicker, Radio, message, Upload, Modal, Checkbox} from 'antd'
import moment from 'moment';
const {TextArea} = Input;
const CheckboxGroup = Checkbox.Group;
const RadioGroup = Radio.Group;
const {RangePicker} = DatePicker;
const options = [
    {label: '优惠券', value: '1'},
    {label: '金币', value: '2'},
    {label: '会员优惠', value: '4'},
];

class Step1 extends PureComponent {
    constructor(props) {
        super(props)
    }

    state = {
        loading: false,
        commitLoading:false,
        icon: [],
        warmIcon:[],
        presellBackground: [],
        previewVisible: false,
        previewImage: '',
        err: false
    };
    // componentDidMount() {
    //     this.props.form.validateFields();
    // }
    componentDidMount = () => {
        const {id} = this.props.location.query;
        if (id) {
            this.getPresale(id)
        }
    }
    getPresale = (id) => {
        fetch.getPresale({id}).then((res) => {
            if (res.result) {
                const {
                    beginTime,
                    deliveryTime,
                    earnestRepayPrice,
                    earnestType,
                    endTime,
                    icon,
                    warmIcon,
                    name,
                    payBeginTime,
                    payEndTime,
                    preferentialWay,
                    remarks,
                    state,
                    earnestPayPrice

                } = res.result;
                const dataTime='YYYY-MM-DD hh:mm:ss';
                const {setFieldsValue} = this.props.form;
                let allMoneyTime=[moment(payBeginTime,dataTime),moment(payEndTime,dataTime)];
                let presellTime=[moment(beginTime,dataTime),moment(endTime,dataTime)];
                this.setState({
                    icon:[{
                        uid: '-1',
                        name: 'xx0.png',
                        status: 'done',
                        url: icon,
                    }],
                    warmIcon:[{
                        uid: '-2',
                        name: 'xxx1.png',
                        status: 'done',
                        url: warmIcon,
                    }],

                })
                setFieldsValue({
                    presellName:name,
                    allMoneyTime:allMoneyTime,
                    earnestDeductionMoney:earnestRepayPrice+'',
                    earnestPaymentMoney: earnestPayPrice+'',
                    presellShipmentsTime:moment(deliveryTime,dataTime),
                    presellTime:presellTime,
                    icon:icon,
                    openClose:state,
                    remark:remarks,
                    warmIcon:warmIcon,
                    paymentDiscountsType:options.filter((item)=>{
                       return  (Number(preferentialWay)&Number(item.value))===Number(item.value);

                    }).map((item)=>{
                        return item.value;
                    }),
                    earnestPaymentType:earnestType
                });

            }
        })
    }
    setPresale = (obj) => {
        const {id,pid} = this.props.location.query;

        const {
            presellName,
            allMoneyTime,
            earnestDeductionMoney,
            earnestPaymentMoney,
            presellShipmentsTime,
            presellTime,
            icon,
            warmIcon,
            openClose,
            remark,
            paymentDiscountsType,
            earnestPaymentType
        } = obj;

        if(!this.state.commitLoading){
            fetch.setPresale({
                "id": id,
                "name": presellName,
                "beginTime": moment(presellTime[0]).format('YYYY-MM-DD HH:mm:ss'),
                "endTime": moment(presellTime[1]).format('YYYY-MM-DD HH:mm:ss'),
                "payBeginTime": moment(allMoneyTime[0]).format('YYYY-MM-DD HH:mm:ss'),
                "payEndTime": moment(allMoneyTime[1]).format('YYYY-MM-DD HH:mm:ss'),
                "deliveryTime": moment(presellShipmentsTime).format('YYYY-MM-DD HH:mm:ss'),
                "state": openClose,
                "earnestType": earnestPaymentType,
                "earnestPayPrice": Number(earnestPaymentMoney),
                "earnestRepayPrice": Number(earnestDeductionMoney),
                "icon": icon,
                "warmIcon":warmIcon ,
                "remarks": remark,
                "preferentialWay": paymentDiscountsType.reduce((total, current) => {
                    return Number(total) + Number(current)
                })
            }).then(res=>{
                    this.setState({
                        commitLoading:false
                    })
                if(res.code==='200'){
                    if(!id){
                        this.props.setData((res.result&&res.result.key)||id,presellName);
                    }else if(!pid){
                        this.props.router.replace({
                            pathname:'/app/home/list'
                        });
                    }else{
                        this.props.router.replace({
                            pathname:'/app/home/add',
                            query:{
                                pid:pid,
                                id:id
                            }
                        });
                        this.props.toView(2)
                    }
                }

            })
        }
        this.setState({
            commitLoading:true
        })
    }

    upload = {
        handleChange: (key) => {
            return ({fileList}) => {
                const response = fileList[0] && fileList[0].response;
                if (response && response.error === 0) {
                    this.props.form.setFieldsValue({
                        [key]: response.url
                    });
                }

                this.setState({[key]: fileList})
            }
        },
        handleCancel: () => {
            this.setState({previewVisible: false})
        },
        handlePreview: (file) => {
            this.setState({
                previewImage: file.url || file.thumbUrl,
                previewVisible: true,
            });
        },
        handleRemove: (key) => {
            return () => {
                this.props.form.setFieldsValue({
                    [key]: undefined
                });
                this.props.form.validateFields([key])
            }
        }
    };
    next = () => {
        this.props.form.validateFields((err, value) => {
            if (!err) {
                this.setPresale(value)
            }
        })
    }
    reset = () => {
        this.setState({
            promotionIcon: []
        });
        this.props.form.resetFields();
    }

    render() {
        const {getFieldDecorator, getFieldsError, getFieldValue,getFieldError, isFieldTouched, isFieldsTouched} = this.props.form;
        const {previewVisible, previewImage, icon,warmIcon,commitLoading} = this.state;
        const {handleChange, handleCancel, handlePreview, handleRemove} = this.upload;
        const {id} = this.props.location.query;
        const year=new Date().getFullYear();
        const month=new Date().getMonth()+1;
        const date=new Date().getDate();
        const currentDate=moment(`${year}-${month}-${date}`);
        const presellTime=[moment(moment(currentDate),"MM-DD-YYYY hh:mm:ss"),moment(moment(currentDate),"MM-DD-YYYY hh:mm:ss").add(5, 'days')];
        const allMoneyTime=[moment(moment(currentDate),"MM-DD-YYYY hh:mm:ss").add(5, 'days'),moment(moment(currentDate),"MM-DD-YYYY hh:mm:ss").add(6, 'days')];
       const  presellShipmentsTime=moment(moment(currentDate),"MM-DD-YYYY hh:mm:ss").add(6, 'days');
        const itemLayout = {
            labelCol: {
                span: 6
            },
            wrapperCol: {
                span: 18
            }
        }
        const uploadButton = (
            <div>
                <Icon type={this.state.loading ? 'loading' : 'plus'}/>
                <div className="ant-upload-text">选择</div>
                <p>png格式</p>
            </div>
        );

        function hasErrors(fieldsError) {
            return Object.keys(fieldsError).some(field => fieldsError[field]);
        }

        return (
            <div className={'step1'}>
                <Form>
                    <Form.Item
                        label={'预售名称：'}
                        {...itemLayout}
                    >
                        {getFieldDecorator('presellName', {
                            rules: [
                                {required: true, message: '请填写预售名称!'},
                                {max: 50, message: '不能超过50个字!'},
                            ],
                            initialValue:''
                        })(
                            <Input disabled={id} placeholder="请输入预售名称"/>
                        )}
                    </Form.Item>
                    <Form.Item
                        label={'预售时间：'}
                        {...itemLayout}
                    >
                        {getFieldDecorator('presellTime', {
                            rules: [{required: true, message: '请选择预售时间!'}],
                            initialValue:presellTime
                        })(
                            <RangePicker
                                style={{width: '100%'}}
                                showTime
                                disabled={id}
                                format="YYYY/MM/DD HH:mm:ss"
                            />
                        )}
                    </Form.Item>
                    <Form.Item
                        label={'全款支付时间：'}
                        {...itemLayout}
                    >
                        {getFieldDecorator('allMoneyTime', {
                            rules: [
                                {required: true, message: '请选择全款支付时间!'},
                                {validator:(rule,value,callback)=>{
                                        const presellTimeEnd=getFieldValue('presellTime')[1]&&getFieldValue('presellTime')[1].valueOf();
                                        const allMoneyTimeEnd=getFieldValue('allMoneyTime')[1]&&getFieldValue('allMoneyTime')[1].valueOf();
                                        if(allMoneyTimeEnd<presellTimeEnd){
                                            callback({message:'全款支付结束时间不能小于预售结束时间！'})
                                        }
                                        else{
                                            callback()
                                        }
                                    }}
                                ],
                            initialValue:allMoneyTime
                        })(
                            <RangePicker
                                style={{width: '100%'}}
                                showTime
                                format="YYYY/MM/DD HH:mm:ss"
                                disabled={getFieldValue('earnestPaymentType') === 2}
                            />
                        )}
                    </Form.Item>
                    <Form.Item
                        label={'预售发货时间：'}
                        {...itemLayout}
                    >
                        {getFieldDecorator('presellShipmentsTime', {
                            rules: [
                                {required: true, message: '请选择预售发货时间!'},
                                {validator:(rule,value,callback)=>{
                                       const allMoneyTimeEnd=getFieldValue('allMoneyTime')[1]&&getFieldValue('allMoneyTime')[1].valueOf();
                                       const presellShipmentsTime=getFieldValue('presellShipmentsTime')&&getFieldValue('presellShipmentsTime').valueOf();
                                       if(presellShipmentsTime<allMoneyTimeEnd){
                                           callback({message:'预售发货时间不能小于全款支付结束时间！'})
                                       }
                                       else{
                                           callback()
                                       }
                                    }}
                                ],
                            initialValue:presellShipmentsTime,

                        })(
                            <DatePicker
                                style={{width: '100%'}}
                                showTime
                                format="YYYY/MM/DD HH:mm:ss"
                            />
                        )}
                    </Form.Item>
                    <Form.Item
                        label={'开启/关闭：'}
                        {...itemLayout}
                    >
                        {getFieldDecorator('openClose', {
                            rules: [{required: true, message: '请选择状态!'}],
                            initialValue: 1
                        })(
                            <RadioGroup name="radiogroup">
                                <Radio value={0}>关闭</Radio>
                                <Radio value={1}>开启</Radio>
                            </RadioGroup>
                        )}
                    </Form.Item>
                    <Form.Item
                        label={'定金支付方式：'}
                        {...itemLayout}
                    >
                        {getFieldDecorator('earnestPaymentType', {
                            initialValue: 1
                        })(
                            <RadioGroup >
                                <Radio  disabled={id} value={1}>按金额支付</Radio>
                                <Radio  disabled={id} value={2}>全款支付定金</Radio>
                            </RadioGroup>
                        )}
                    </Form.Item>
                    {
                        getFieldValue('earnestPaymentType') === 1 &&
                            <div>
                                <Form.Item
                                    label={'定金支付金额：'}
                                    {...itemLayout}
                                >
                                    {getFieldDecorator('earnestPaymentMoney', {
                                        rules: [
                                            {required: true, message: '请填写定金支付金额!'},
                                            {pattern: /^[\d]+?$/, message: '请填写数字!'}
                                        ],
                                        initialValue:0
                                    })(
                                        <Input  disabled={id} placeholder="请输入定金支付金额"/>
                                    )}
                                </Form.Item>
                                <Form.Item
                                    label={'定金抵扣金额：'}
                                    {...itemLayout}
                                >
                                    {getFieldDecorator('earnestDeductionMoney', {
                                        rules: [
                                            {required: true, message: '请填写定金抵扣金额!'},
                                            {pattern: /^[\d]+?$/, message: '请填写数字!'}
                                        ],
                                        initialValue:0
                                    })(
                                        <Input  disabled={id} placeholder="请输入定金抵扣金额"/>
                                    )}
                                </Form.Item>
                            </div>

                    }

                    {getFieldValue('earnestPaymentType') === 1&&<p className={'paymentHint'}>温馨提示：支付全款时定金将进行退款</p>}
                    {getFieldValue('earnestPaymentType') === 2&&<p className={'paymentHint'}>全款支付定金则商品直接加入购物袋购买</p>}
                    {
                        getFieldValue('earnestPaymentType') === 1 &&  <Form.Item
                            label={'预售开始前角标：'}
                            {...itemLayout}
                        >
                            {getFieldDecorator('warmIcon', {
                                rules: [
                                    // {required: true, message: '请添加角标'},
                                ],
                            })(
                                <div className="clearfix">
                                    <Upload
                                        accept={'.png'}
                                        listType="picture-card"
                                        action={'/upload/picture/uploadERP'}
                                        fileList={warmIcon}
                                        onPreview={handlePreview}
                                        onChange={handleChange('warmIcon')}
                                        onRemove={handleRemove('warmIcon')}
                                        beforeUpload={() => {
                                            return true
                                        }}
                                    >
                                        {warmIcon.length >= 1 ? null : uploadButton}
                                    </Upload>
                                </div>
                            )}
                        </Form.Item>
                    }
                    {
                        getFieldValue('earnestPaymentType') === 1 &&  <Form.Item
                            label={'预售进行中角标：'}
                            {...itemLayout}
                        >
                            {getFieldDecorator('icon', {
                                rules: [
                                    // {required: true, message: '请添加角标'},
                                ],
                            })(
                                <div className="clearfix">
                                    <Upload
                                        accept={'.png'}
                                        listType="picture-card"
                                        action={'/upload/picture/uploadERP'}
                                        fileList={icon}
                                        onPreview={handlePreview}
                                        onChange={handleChange('icon')}
                                        onRemove={handleRemove('icon')}
                                        beforeUpload={() => {
                                            return true
                                        }}
                                    >
                                        {icon.length >= 1 ? null : uploadButton}
                                    </Upload>
                                </div>
                            )}
                        </Form.Item>
                    }

                    <Form.Item
                        label={'支付优惠方式：'}
                        {...itemLayout}
                    >
                        {getFieldDecorator('paymentDiscountsType', {
                            rules: [
                                {required: true, message: '请至少选择一项！'},
                            ],
                            initialValue:[]
                        })(
                            <CheckboxGroup options={options} onChange={this.onChange}/>
                        )}
                    </Form.Item>
                    <Form.Item
                        label={'备注：'}
                        {...itemLayout}
                    >
                        {getFieldDecorator('remark', {
                            rules: [
                                // {required: true, message: '请填写定金支付金额!'},
                            ],
                            initialValue:''
                        })(
                            <TextArea rows={4}/>
                        )}
                    </Form.Item>
                </Form>
                <Modal visible={previewVisible} footer={null} onCancel={handleCancel}>
                    <img alt="example" style={{width: '100%'}} src={previewImage}/>
                </Modal>
                <div className={'step1_submit_wrap'}>
                    {
                        !id&&
                        <Button disabled={hasErrors(getFieldsError())||commitLoading} style={{marginRight: 30}} type={'primary'}
                                onClick={this.next}>下一步</Button>
                    }

                    {
                        id&&
                        <Button disabled={hasErrors(getFieldsError())||commitLoading} style={{marginRight: 30}} type={'primary'}
                              onClick={this.next}>完成</Button>}

                    <Button onClick={this.reset}>重置</Button>
                </div>
            </div>


        )
    }

}

export default Form.create()(Step1);